package net.crazyblock.ral;

import java.util.List;

import net.crazyblock.ral.bl.ColorDao;
import net.crazyblock.ral.bo.RalColor;
import net.crazyblock.ral.db.RalColorSQLiteOpenHelper;
import net.crazyblock.ral.utils.StringTools;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends Activity implements
		AdapterView.OnItemClickListener, View.OnClickListener {

	private ListView lv;
	private List<RalColor> ralColors;
	private EditText et_search;
	private ColorDao dao;
	private ViewGroup mContainer;
	private ViewGroup searchBar;
	private ImageView mImageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		// RalColorSQLiteOpenHelper helper = new RalColorSQLiteOpenHelper(this);
		// helper.getWritableDatabase();
		dao = new ColorDao();
		ralColors = dao.findAllColors(this);
		lv = (ListView) findViewById(R.id.lv);
		mContainer = (ViewGroup) findViewById(R.id.container);
		searchBar = (ViewGroup) findViewById(R.id.item_search);
		mImageView = (ImageView) findViewById(R.id.big_color);
		lv.setAdapter(new MyAdapter());
		lv.setOnItemClickListener(this);// 此处this是因为此activity继承了AdapterView.OnItemClickListener
		Button bt_search = (Button) findViewById(R.id.bt_search);
		et_search = (EditText) findViewById(R.id.et_search);

		// Prepare the ImageView
		mImageView.setClickable(true);
		mImageView.setFocusable(true);
		mImageView.setOnClickListener(this);
		// Since we are caching large views, we want to keep their cache
		// between each animation
		mContainer
				.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);

		bt_search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub
				et_search.setText("");
				ralColors = dao.findAllColors(HomeActivity.this);
				et_search.clearFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

				// �ر������
				// mm.showSoftInputFromInputMethod(et_search.getWindowToken()
				// , 0);

				imm.hideSoftInputFromWindow(et_search.getWindowToken(), 0);

			}
		});

		et_search.addTextChangedListener(new android.text.TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

				String str = et_search.getText().toString().trim();
				if (!TextUtils.isEmpty(str)) {

					ralColors = dao.findLikeRal(HomeActivity.this, str);
					lv.setAdapter(new MyAdapter());
					if (ralColors.isEmpty()) {
						Toast.makeText(HomeActivity.this, "查不到此颜色值", 0).show();
					}
				}

			}
		});
	}

	/**
	 * Setup a new 3D rotation on the container view. 在容器视图新建一个3D旋转
	 * 
	 * @param position
	 *            the item that was clicked to show a picture, or -1 to show the
	 *            list
	 * @param start
	 *            the start angle at which the rotation must begin
	 * @param end
	 *            the end angle of the rotation
	 */
	private void applyRotation(int position, float start, float end) {
		// Find the center of the container
		final float centerX = mContainer.getWidth() / 2.0f;
		final float centerY = mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// 使用提供的参数新建一个3D旋转动画
		// The animation listener is used to trigger the next animation
		// 动画监听器用于触发下一个动画
		final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end,
				centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(position));

		mContainer.startAnimation(rotation);

	}

	private class MyAdapter extends BaseAdapter {

		private static final String tag = "MyAdapter";

		/**
		 * ����listview�й��ж��� ����Ŀ
		 * 
		 * @return
		 */
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ralColors.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// Product product = products.get(position);
			View view;
			ViewHolder holder;
			RalColor ralColor = ralColors.get(position);
			// if-else语句用来优化listView，避免创建过多对象，影响性能
			if (convertView == null) {
				view = View.inflate(HomeActivity.this, R.layout.listview_item,
						null);
				holder = new ViewHolder();
				holder.tv_color = (TextView) view.findViewById(R.id.tv_color);
				holder.tv_ralvalue = (TextView) view
						.findViewById(R.id.tv_ralvalue);
				holder.tv_rgb_hex = (TextView) view
						.findViewById(R.id.tv_rgb_hex);
				holder.tv_rgb = (TextView) view.findViewById(R.id.tv_rgb);
				view.setTag(holder);
			} else {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			}

			holder.tv_color.setBackgroundColor(0xff000000 + Integer.parseInt(
					ralColor.getHexValue(), 16));

			holder.tv_ralvalue.setText("Ral:"
					+ fixLengthTo3(ralColor.getRalHValue()) + " "
					+ fixLengthTo2(ralColor.getRalLValue()) + " "
					+ fixLengthTo2(ralColor.getRalCValue()));

			holder.tv_rgb_hex.setText("RGB:" + ralColor.getHexValue());

			holder.tv_rgb.setText("RGB:"
					+ StringTools.hexToRGB(ralColor.getHexValue()));
			return view;

		}

		public String fixLengthTo3(String value) {
			if (value.length() < 3) {
				String str = null;
				switch (value.length()) {
				case 1:
					str = "00" + value;
					break;
				case 2:
					str = "0" + value;
					break;
				default:
					break;
				}
				return str;
			} else {
				return value;
			}

		}

		public String fixLengthTo2(String value) {
			if (value.length() < 2) {
				String str = null;
				switch (value.length()) {
				case 1:
					str = "0" + value;
					break;
				default:
					break;
				}
				return str;
			} else {
				return value;
			}

		}

	}

	/**
	 * This class listens for the end of the first half of the animation.
	 * 这个类监听前半部分动画的结束 It then posts a new action that effectively swaps the
	 * views when the container is rotated 90 degrees and thus invisible.
	 * 然后传输一个动作使视图在旋转90°后不可见
	 */
	private final class DisplayNextView implements Animation.AnimationListener {
		private final int mPosition;

		private DisplayNextView(int position) {
			mPosition = position;
		}

		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			mContainer.post(new SwapViews(mPosition));
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation. 这个类应答切换视图并且开始后半部分动画
	 */
	private final class SwapViews implements Runnable {
		private final int mPosition;

		public SwapViews(int position) {
			mPosition = position;
		}

		public void run() {
			final float centerX = mContainer.getWidth() / 2.0f;
			final float centerY = mContainer.getHeight() / 2.0f;
			Rotate3dAnimation rotation;

			if (mPosition > -1) {
				lv.setVisibility(View.GONE);
				searchBar.setVisibility(View.INVISIBLE);
				mImageView.setVisibility(View.VISIBLE);
				mImageView.requestFocus();

				rotation = new Rotate3dAnimation(90, 180, centerX, centerY,
						310.0f, false);
			} else {
				mImageView.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				searchBar.setVisibility(View.VISIBLE);
				lv.requestFocus();

				rotation = new Rotate3dAnimation(90, 0, centerX, centerY,
						310.0f, false);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			mContainer.startAnimation(rotation);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		applyRotation(-1, 180, 90);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		RalColor color = ralColors.get(position);

		mImageView.setBackgroundColor(0xff000000 + Integer.parseInt(
				color.getHexValue(), 16));

		applyRotation(position, 0, 90);
	}

	class ViewHolder {
		TextView tv_color;
		TextView tv_ralvalue;
		TextView tv_rgb_hex;
		TextView tv_rgb;
	}

}
